// API基础URL
const API_BASE_URL = '/api';

// DOM元素（将在DOMContentLoaded中初始化）
let loginSection, mainContent, loginForm, logoutBtn;
let addGoodsModal, addGoodsForm, editGoodsModal, editGoodsForm;
let viewInboundModal, viewOutboundModal, inboundDetailContent, outboundDetailContent;
let addInstructionModal, addInstructionForm;
let addTransferModal, addTransferForm;
let closeModalBtns;

// 表格元素
let inboundTableBody, outboundTableBody, instructionTableBody, instructionHistoryTableBody;
let inventoryQueryTableBody, stocktakingTableBody, transferTableBody;
let inventoryDetailsTableBody;

// 按钮元素
let addInboundBtn, addOutboundBtn, addInstructionBtn, addTransferBtn;
let searchInventoryBtn, startStocktakingBtn;
let refreshLocationStatusBtn, refreshLocationMaterialBtn;
let filterInstructionsBtn;

// 输入元素
let inventorySearch, materialFilter;
let startDateFilter, endDateFilter, instructionTypeFilter;

// 统计元素
let totalGoodsTypes, totalInventoryQuantity, occupiedLocations, emptyLocations;

// JWT令牌
let authToken = localStorage.getItem('authToken');

// 当前编辑的货物信息
let currentEditGoods = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    // 初始化DOM元素
    initializeDOMElements();
    
    // 检查用户是否已登录
    if (authToken) {
        showMainContent();
        loadAllData();
    } else {
        showLoginSection();
    }
    
    // 绑定事件监听器
    bindEventListeners();
});

// 初始化DOM元素
function initializeDOMElements() {
    // 认证相关元素
    loginSection = document.getElementById('loginSection');
    mainContent = document.getElementById('mainContent');
    loginForm = document.getElementById('loginForm');
    logoutBtn = document.getElementById('logoutBtn');

    // 模态框元素
    addGoodsModal = document.getElementById('addGoodsModal');
    addGoodsForm = document.getElementById('addGoodsForm');
    editGoodsModal = document.getElementById('editGoodsModal');
    editGoodsForm = document.getElementById('editGoodsForm');
    viewInboundModal = document.getElementById('viewInboundModal');
    viewOutboundModal = document.getElementById('viewOutboundModal');
    inboundDetailContent = document.getElementById('inboundDetailContent');
    outboundDetailContent = document.getElementById('outboundDetailContent');
    addInstructionModal = document.getElementById('addInstructionModal');
    addInstructionForm = document.getElementById('addInstructionForm');
    addTransferModal = document.getElementById('addTransferModal');
    addTransferForm = document.getElementById('addTransferForm');
    closeModalBtns = document.querySelectorAll('.close');

    // 表格元素
    inboundTableBody = document.querySelector('#inboundTable tbody');
    outboundTableBody = document.querySelector('#outboundTable tbody');
    instructionTableBody = document.querySelector('#instructionTable tbody');
    instructionHistoryTableBody = document.querySelector('#instructionHistoryTable tbody');
    inventoryQueryTableBody = document.querySelector('#inventoryQueryTable tbody');
    stocktakingTableBody = document.querySelector('#stocktakingTable tbody');
    transferTableBody = document.querySelector('#transferTable tbody');
    inventoryDetailsTableBody = document.querySelector('#inventoryDetailsTable tbody');

    // 按钮元素
    addInboundBtn = document.getElementById('addInboundBtn');
    addOutboundBtn = document.getElementById('addOutboundBtn');
    addInstructionBtn = document.getElementById('addInstructionBtn');
    addTransferBtn = document.getElementById('addTransferBtn');
    searchInventoryBtn = document.getElementById('searchInventoryBtn');
    startStocktakingBtn = document.getElementById('startStocktakingBtn');
    refreshLocationStatusBtn = document.getElementById('refreshLocationStatusBtn');
    refreshLocationMaterialBtn = document.getElementById('refreshLocationMaterialBtn');
    filterInstructionsBtn = document.getElementById('filterInstructionsBtn');

    // 输入元素
    inventorySearch = document.getElementById('inventorySearch');
    materialFilter = document.getElementById('materialFilter');
    startDateFilter = document.getElementById('startDateFilter');
    endDateFilter = document.getElementById('endDateFilter');
    instructionTypeFilter = document.getElementById('instructionTypeFilter');

    // 统计元素
    totalGoodsTypes = document.getElementById('totalGoodsTypes');
    totalInventoryQuantity = document.getElementById('totalInventoryQuantity');
    occupiedLocations = document.getElementById('occupiedLocations');
    emptyLocations = document.getElementById('emptyLocations');
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('开始绑定事件监听器...');
    
    // 登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
        console.log('已绑定登录表单提交事件');
    }
    
    // 登出按钮
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
        console.log('已绑定登出按钮点击事件');
    }
    
    // 关闭模态框按钮
    if (closeModalBtns) {
        closeModalBtns.forEach(btn => {
            btn.addEventListener('click', closeAllModals);
        });
        console.log('已绑定关闭模态框按钮点击事件');
    }
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        const modals = [addGoodsModal, editGoodsModal, viewInboundModal, viewOutboundModal, 
                       addInstructionModal, addTransferModal];
        if (modals.includes(event.target)) {
            closeAllModals();
        }
    });
    
    // 添加货物表单提交
    if (addGoodsForm) {
        addGoodsForm.addEventListener('submit', handleAddGoodsSubmit);
    }
    
    // 编辑货物表单提交
    if (editGoodsForm) {
        editGoodsForm.addEventListener('submit', handleEditGoodsSubmit);
    }
    
    // 创建指令表单提交
    if (addInstructionForm) {
        addInstructionForm.addEventListener('submit', handleAddInstructionSubmit);
    }
    
    // 创建移库单表单提交
    if (addTransferForm) {
        addTransferForm.addEventListener('submit', handleAddTransferSubmit);
    }
    
    // 创建入库单据按钮
    if (addInboundBtn) {
        addInboundBtn.addEventListener('click', function() {
            window.location.href = 'create_inbound.html';
        });
    }
    
    // 创建出库单据按钮
    if (addOutboundBtn) {
        addOutboundBtn.addEventListener('click', function() {
            window.location.href = 'create_outbound.html';
        });
    }
    
    // 创建指令按钮
    if (addInstructionBtn) {
        addInstructionBtn.addEventListener('click', openAddInstructionModal);
    }
    
    // 创建移库单按钮
    if (addTransferBtn) {
        addTransferBtn.addEventListener('click', openAddTransferModal);
    }
    
    // 库存搜索按钮
    if (searchInventoryBtn) {
        searchInventoryBtn.addEventListener('click', handleInventorySearch);
    }
    
    // 开始盘点按钮
    if (startStocktakingBtn) {
        startStocktakingBtn.addEventListener('click', handleStartStocktaking);
    }
    
    // 刷新货位状态视图按钮
    if (refreshLocationStatusBtn) {
        refreshLocationStatusBtn.addEventListener('click', handleRefreshLocationStatus);
    }
    
    // 刷新货位物料视图按钮
    if (refreshLocationMaterialBtn) {
        refreshLocationMaterialBtn.addEventListener('click', handleRefreshLocationMaterial);
    }
    
    // 筛选指令历史按钮
    if (filterInstructionsBtn) {
        filterInstructionsBtn.addEventListener('click', handleFilterInstructions);
    }
    
    console.log('事件监听器绑定完成');
}

// 显示登录界面
function showLoginSection() {
    console.log('显示登录界面');
    if (loginSection) loginSection.style.display = 'block';
    if (mainContent) mainContent.style.display = 'none';
}

// 显示主内容界面
function showMainContent() {
    console.log('显示主内容界面');
    if (loginSection) loginSection.style.display = 'none';
    if (mainContent) mainContent.style.display = 'block';
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            authToken = data.data.token;
            localStorage.setItem('authToken', authToken);
            showMainContent();
            loadAllData();
        } else {
            alert('登录失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('登录失败:', error);
        alert('登录失败');
    });
}

// 处理登出
function handleLogout() {
    authToken = null;
    localStorage.removeItem('authToken');
    showLoginSection();
}

// 关闭所有模态框
function closeAllModals() {
    console.log('关闭所有模态框');
    const modals = [addGoodsModal, editGoodsModal, viewInboundModal, viewOutboundModal, 
                   addInstructionModal, addTransferModal];
    modals.forEach(modal => {
        if (modal) modal.style.display = 'none';
    });
    
    // 重置表单
    if (addGoodsForm) addGoodsForm.reset();
    if (editGoodsForm) editGoodsForm.reset();
    if (addInstructionForm) addInstructionForm.reset();
    if (addTransferForm) addTransferForm.reset();
}

// 打开创建指令模态框
function openAddInstructionModal() {
    console.log('打开创建指令模态框');
    if (addInstructionModal) {
        if (addInstructionForm) addInstructionForm.reset();
        addInstructionModal.style.display = 'block';
    }
}

// 打开创建移库单模态框
function openAddTransferModal() {
    console.log('打开创建移库单模态框');
    if (addTransferModal) {
        if (addTransferForm) addTransferForm.reset();
        addTransferModal.style.display = 'block';
    }
}

// 处理添加货物表单提交
function handleAddGoodsSubmit(event) {
    event.preventDefault();
    
    const goodsData = {
        name: document.getElementById('goodsName').value,
        sku: document.getElementById('goodsSku').value,
        quantity: parseInt(document.getElementById('goodsQuantity').value) || 0,
        location: document.getElementById('goodsLocation').value,
        status: document.getElementById('goodsStatus').value,
        batchNumber: document.getElementById('goodsBatch').value
    };
    
    createGoods(goodsData);
}

// 处理编辑货物表单提交
function handleEditGoodsSubmit(event) {
    event.preventDefault();
    
    const id = document.getElementById('editGoodsId').value;
    const goodsData = {
        name: document.getElementById('editGoodsName').value,
        sku: document.getElementById('editGoodsSku').value,
        quantity: parseInt(document.getElementById('editGoodsQuantity').value) || 0,
        location: document.getElementById('editGoodsLocation').value,
        status: document.getElementById('editGoodsStatus').value,
        batchNumber: document.getElementById('editGoodsBatch').value
    };
    
    updateGoods(id, goodsData);
}

// 处理创建指令表单提交
function handleAddInstructionSubmit(event) {
    event.preventDefault();
    
    const instructionData = {
        taskId: document.getElementById('taskId').value,
        taskType: document.getElementById('taskType').value,
        palletId: document.getElementById('palletId').value,
        startLocation: document.getElementById('startLocation').value,
        targetLocation: document.getElementById('targetLocation').value,
        startDevice: document.getElementById('startDevice').value,
        endDevice: document.getElementById('endDevice').value,
        materialCode: document.getElementById('materialCode').value,
        materialName: document.getElementById('materialName').value,
        executeQuantity: parseInt(document.getElementById('executeQuantity').value) || 0
    };
    
    createInstruction(instructionData);
}

// 处理创建移库单表单提交
function handleAddTransferSubmit(event) {
    event.preventDefault();
    
    const transferData = {
        goodsId: parseInt(document.getElementById('transferGoodsId').value),
        sourceLocation: document.getElementById('sourceLocation').value,
        targetLocation: document.getElementById('targetLocation').value,
        quantity: parseInt(document.getElementById('transferQuantity').value) || 1
    };
    
    createTransfer(transferData);
}

// 处理库存搜索
function handleInventorySearch() {
    const keyword = inventorySearch ? inventorySearch.value : '';
    searchInventory(keyword);
}

// 处理开始盘点
function handleStartStocktaking() {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要开始盘点吗？')) {
        // 这里可以实现开始盘点的逻辑
        alert('开始盘点功能待实现');
    }
}

// 处理刷新货位状态视图
function handleRefreshLocationStatus() {
    // 这里可以实现刷新货位状态视图的逻辑
    alert('刷新货位状态视图功能待实现');
}

// 处理刷新货位物料视图
function handleRefreshLocationMaterial() {
    // 这里可以实现刷新货位物料视图的逻辑
    alert('刷新货位物料视图功能待实现');
}

// 处理筛选指令历史
function handleFilterInstructions() {
    const type = instructionTypeFilter ? instructionTypeFilter.value : '';
    const startDate = startDateFilter ? startDateFilter.value : '';
    const endDate = endDateFilter ? endDateFilter.value : '';
    filterInstructions(type, startDate, endDate);
}

// 加载所有数据
function loadAllData() {
    loadInboundDocuments();
    loadOutboundDocuments();
    loadInstructions();
    loadInventoryData();
    loadInstructionHistory();
}

// 加载入库单据数据
function loadInboundDocuments() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/inbound`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInboundTable(data.data);
            }
        })
        .catch(error => {
            console.error('加载入库单据数据失败:', error);
        });
}

// 渲染入库单据表格
function renderInboundTable(documents) {
    if (!inboundTableBody) return;
    
    inboundTableBody.innerHTML = '';
    
    documents.forEach(doc => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${doc.id}</td>
            <td>${doc.goods_id}</td>
            <td>${doc.supplier}</td>
            <td>${doc.quantity}</td>
            <td>${formatDate(doc.expected_arrival_date)}</td>
            <td>${getDocumentStatusText(doc.status)}</td>
            <td>
                <button class="btn-primary" onclick="viewInboundDocument(${doc.id})">查看</button>
                <button class="btn-primary" onclick="updateInboundStatus(${doc.id}, 'received')">接收</button>
                <button class="btn-primary" onclick="updateInboundStatus(${doc.id}, 'completed')">完成</button>
            </td>
        `;
        inboundTableBody.appendChild(row);
    });
}

// 加载出库单据数据
function loadOutboundDocuments() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/outbound`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderOutboundTable(data.data);
            }
        })
        .catch(error => {
            console.error('加载出库单据数据失败:', error);
        });
}

// 渲染出库单据表格
function renderOutboundTable(documents) {
    if (!outboundTableBody) return;
    
    outboundTableBody.innerHTML = '';
    
    documents.forEach(doc => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${doc.id}</td>
            <td>${doc.goods_id}</td>
            <td>${doc.customer}</td>
            <td>${doc.quantity}</td>
            <td>${formatDate(doc.expected_pickup_date)}</td>
            <td>${getDocumentStatusText(doc.status)}</td>
            <td>
                <button class="btn-primary" onclick="viewOutboundDocument(${doc.id})">查看</button>
                <button class="btn-primary" onclick="updateOutboundStatus(${doc.id}, 'picked')">拣货</button>
                <button class="btn-primary" onclick="updateOutboundStatus(${doc.id}, 'completed')">完成</button>
            </td>
        `;
        outboundTableBody.appendChild(row);
    });
}

// 加载指令数据
function loadInstructions() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/instructions`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInstructionTable(data.data);
            }
        })
        .catch(error => {
            console.error('加载指令数据失败:', error);
        });
}

// 渲染指令表格
function renderInstructionTable(instructions) {
    if (!instructionTableBody) return;
    
    instructionTableBody.innerHTML = '';
    
    instructions.forEach(instruction => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${instruction.id}</td>
            <td>${instruction.task_id}</td>
            <td>${instruction.task_type}</td>
            <td>${instruction.pallet_id || '-'}</td>
            <td>${instruction.start_location || '-'}</td>
            <td>${instruction.target_location || '-'}</td>
            <td>${instruction.start_device || '-'}</td>
            <td>${instruction.end_device || '-'}</td>
            <td>${instruction.material_code || '-'}</td>
            <td>${instruction.material_name || '-'}</td>
            <td>${instruction.execute_quantity || 0}</td>
            <td>${instruction.instruction_result || '-'}</td>
            <td>${instruction.completion_method || '-'}</td>
            <td>${instruction.completion_time ? formatDate(instruction.completion_time) : '-'}</td>
            <td>
                <button class="btn-primary" onclick="viewInstruction(${instruction.id})">查看</button>
                <button class="btn-primary" onclick="deleteInstruction(${instruction.id})">删除</button>
            </td>
        `;
        instructionTableBody.appendChild(row);
    });
}

// 加载库存数据
function loadInventoryData() {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/goods`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInventoryQueryTable(data.data);
                renderInventoryDetailsTable(data.data);
                updateInventoryStats(data.data);
            }
        })
        .catch(error => {
            console.error('加载库存数据失败:', error);
        });
}

// 渲染库存查询表格
function renderInventoryQueryTable(goodsList) {
    if (!inventoryQueryTableBody) return;
    
    inventoryQueryTableBody.innerHTML = '';
    
    goodsList.forEach(goods => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${goods.id}</td>
            <td>${goods.name}</td>
            <td>${goods.sku}</td>
            <td>${goods.quantity}</td>
            <td>${goods.location || '-'}</td>
            <td>${getStatusText(goods.status)}</td>
        `;
        inventoryQueryTableBody.appendChild(row);
    });
}

// 渲染库存明细表格
function renderInventoryDetailsTable(goodsList) {
    if (!inventoryDetailsTableBody) return;
    
    inventoryDetailsTableBody.innerHTML = '';
    
    goodsList.forEach(goods => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${goods.id}</td>
            <td>${goods.name}</td>
            <td>${goods.sku}</td>
            <td>${goods.quantity}</td>
            <td>${goods.location || '-'}</td>
            <td>${getStatusText(goods.status)}</td>
            <td>${goods.batch_number || '-'}</td>
            <td>${goods.expiry_date ? formatDate(goods.expiry_date) : '-'}</td>
            <td>
                <button class="btn-primary" onclick='openEditGoodsModal(${JSON.stringify(goods).replace(/'/g, "\\'")})'>编辑</button>
                <button class="btn-primary" onclick="deleteGoods(${goods.id})">删除</button>
            </td>
        `;
        inventoryDetailsTableBody.appendChild(row);
    });
}

// 更新库存统计
function updateInventoryStats(goodsList) {
    if (!totalGoodsTypes || !totalInventoryQuantity || !occupiedLocations || !emptyLocations) return;
    
    totalGoodsTypes.textContent = goodsList.length;
    
    let totalQuantity = 0;
    let occupiedCount = 0;
    let emptyCount = 0;
    
    goodsList.forEach(goods => {
        totalQuantity += goods.quantity;
        if (goods.status === 'inStock') {
            occupiedCount++;
        } else {
            emptyCount++;
        }
    });
    
    totalInventoryQuantity.textContent = totalQuantity;
    occupiedLocations.textContent = occupiedCount;
    emptyLocations.textContent = emptyCount;
}

// 加载指令历史数据
function loadInstructionHistory() {
    // 指令历史数据与当前指令数据相同，这里可以添加筛选逻辑
    loadInstructions();
}

// 筛选指令历史
function filterInstructions(type, startDate, endDate) {
    // 这里可以实现指令历史筛选逻辑
    alert('指令历史筛选功能待实现');
}

// 搜索库存
function searchInventory(keyword) {
    if (!authToken) return;
    
    fetch(`${API_BASE_URL}/goods`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let filteredGoods = data.data;
                if (keyword) {
                    filteredGoods = data.data.filter(goods => 
                        goods.name.includes(keyword) || goods.sku.includes(keyword)
                    );
                }
                renderInventoryQueryTable(filteredGoods);
            }
        })
        .catch(error => {
            console.error('搜索库存数据失败:', error);
        });
}

// 获取单据状态文本
function getDocumentStatusText(status) {
    const statusMap = {
        'pending': '待处理',
        'received': '已接收',
        'picked': '已拣货',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 获取货物状态文本
function getStatusText(status) {
    const statusMap = {
        'inStock': '在库',
        'outStock': '出库',
        'reserved': '预留'
    };
    return statusMap[status] || status;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 查看入库单据详情
function viewInboundDocument(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('查看入库单据详情，ID:', id);
    
    fetch(`${API_BASE_URL}/inbound/${id}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderInboundDetail(data.data);
            if (viewInboundModal) {
                viewInboundModal.style.display = 'block';
            }
        } else {
            alert('获取入库单据详情失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('获取入库单据详情失败:', error);
        alert('获取入库单据详情失败');
    });
}

// 渲染入库单据详情
function renderInboundDetail(document) {
    if (!inboundDetailContent) return;
    
    const detailHTML = `
        <div class="document-detail">
            <div class="detail-row">
                <span class="detail-label">单据ID:</span>
                <span class="detail-value">${document.id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">货物ID:</span>
                <span class="detail-value">${document.goods_id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">供应商:</span>
                <span class="detail-value">${document.supplier}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">数量:</span>
                <span class="detail-value">${document.quantity}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">预计到达日期:</span>
                <span class="detail-value">${formatDate(document.expected_arrival_date)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">实际到达日期:</span>
                <span class="detail-value">${document.actual_arrival_date ? formatDate(document.actual_arrival_date) : '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">状态:</span>
                <span class="detail-value">${getDocumentStatusText(document.status)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">操作员:</span>
                <span class="detail-value">${document.operator || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">备注:</span>
                <span class="detail-value">${document.notes || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">${formatDate(document.created_at)}</span>
            </div>
            ${document.status === 'cancelled' ? `
            <div class="detail-row">
                <span class="detail-label">取消原因:</span>
                <span class="detail-value">${document.cancellation_reason || '-'}</span>
            </div>
            ` : ''}
        </div>
    `;
    
    inboundDetailContent.innerHTML = detailHTML;
}

// 查看出库单据详情
function viewOutboundDocument(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('查看出库单据详情，ID:', id);
    
    fetch(`${API_BASE_URL}/outbound/${id}`, {
        headers: {
            'Authorization': `Bearer ${authToken}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderOutboundDetail(data.data);
            if (viewOutboundModal) {
                viewOutboundModal.style.display = 'block';
            }
        } else {
            alert('获取出库单据详情失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('获取出库单据详情失败:', error);
        alert('获取出库单据详情失败');
    });
}

// 渲染出库单据详情
function renderOutboundDetail(document) {
    if (!outboundDetailContent) return;
    
    const detailHTML = `
        <div class="document-detail">
            <div class="detail-row">
                <span class="detail-label">单据ID:</span>
                <span class="detail-value">${document.id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">货物ID:</span>
                <span class="detail-value">${document.goods_id}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">客户:</span>
                <span class="detail-value">${document.customer}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">数量:</span>
                <span class="detail-value">${document.quantity}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">预计提货日期:</span>
                <span class="detail-value">${formatDate(document.expected_pickup_date)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">实际提货日期:</span>
                <span class="detail-value">${document.actual_pickup_date ? formatDate(document.actual_pickup_date) : '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">状态:</span>
                <span class="detail-value">${getDocumentStatusText(document.status)}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">操作员:</span>
                <span class="detail-value">${document.operator || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">备注:</span>
                <span class="detail-value">${document.notes || '-'}</span>
            </div>
            <div class="detail-row">
                <span class="detail-label">创建时间:</span>
                <span class="detail-value">${formatDate(document.created_at)}</span>
            </div>
            ${document.status === 'cancelled' ? `
            <div class="detail-row">
                <span class="detail-label">取消原因:</span>
                <span class="detail-value">${document.cancellation_reason || '-'}</span>
            </div>
            ` : ''}
        </div>
    `;
    
    outboundDetailContent.innerHTML = detailHTML;
}

// 查看指令详情
function viewInstruction(id) {
    alert(`查看指令详情功能待实现，指令ID: ${id}`);
    // 这里可以实现查看详情功能
}

// 更新入库单据状态
function updateInboundStatus(id, status) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/inbound/${id}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ status })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('入库单据状态更新成功');
            loadInboundDocuments();
        } else {
            alert('状态更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新入库单据状态失败:', error);
        alert('状态更新失败');
    });
}

// 更新出库单据状态
function updateOutboundStatus(id, status) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/outbound/${id}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify({ status })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('出库单据状态更新成功');
            loadOutboundDocuments();
        } else {
            alert('状态更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新出库单据状态失败:', error);
        alert('状态更新失败');
    });
}

// 创建指令
function createInstruction(instructionData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('创建指令数据:', instructionData);
    
    fetch(`${API_BASE_URL}/instructions`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(instructionData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('指令创建响应:', data);
        if (data.success) {
            alert('指令创建成功');
            closeAllModals();
            loadInstructions();
        } else {
            alert('指令创建失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建指令失败:', error);
        alert('创建指令失败');
    });
}

// 删除指令
function deleteInstruction(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要删除这个指令吗？')) {
        fetch(`${API_BASE_URL}/instructions/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('指令删除成功');
                loadInstructions();
            } else {
                alert('指令删除失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('删除指令失败:', error);
            alert('删除指令失败');
        });
    }
}

// 创建货物
function createGoods(goodsData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/goods`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(goodsData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('货物创建成功');
            closeAllModals();
            loadInventoryData();
        } else {
            alert('货物创建失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('创建货物失败:', error);
        alert('创建货物失败');
    });
}

// 更新货物
function updateGoods(id, goodsData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    fetch(`${API_BASE_URL}/goods/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`
        },
        body: JSON.stringify(goodsData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('货物更新成功');
            closeAllModals();
            loadInventoryData();
        } else {
            alert('货物更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('更新货物失败:', error);
        alert('更新货物失败');
    });
}

// 删除货物
function deleteGoods(id) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    if (confirm('确定要删除这个货物吗？')) {
        fetch(`${API_BASE_URL}/goods/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('货物删除成功');
                loadInventoryData();
            } else {
                alert('货物删除失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('删除货物失败:', error);
            alert('删除货物失败');
        });
    }
}

// 创建移库单
function createTransfer(transferData) {
    if (!authToken) {
        alert('请先登录');
        return;
    }
    
    console.log('创建移库单数据:', transferData);
    
    // 这里可以实现创建移库单的逻辑
    alert('创建移库单功能待实现');
    closeAllModals();
}

// 打开编辑货物模态框
function openEditGoodsModal(goods) {
    console.log('打开编辑货物模态框:', goods);
    if (editGoodsModal) {
        // 填充表单数据
        document.getElementById('editGoodsId').value = goods.id;
        document.getElementById('editGoodsName').value = goods.name;
        document.getElementById('editGoodsSku').value = goods.sku;
        document.getElementById('editGoodsQuantity').value = goods.quantity;
        document.getElementById('editGoodsLocation').value = goods.location || '';
        document.getElementById('editGoodsStatus').value = goods.status;
        document.getElementById('editGoodsBatch').value = goods.batch_number || '';
        
        currentEditGoods = goods;
        editGoodsModal.style.display = 'block';
    }
}